<template>
  <div class="create-logistics">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="物流单号" prop="trackingNumber">
        <el-input v-model="form.trackingNumber" placeholder="请输入物流单号"></el-input>
      </el-form-item>
      
      <el-form-item label="物流公司" prop="carrierName">
        <el-input v-model="form.carrierName" placeholder="请输入物流公司"></el-input>
      </el-form-item>

      <el-form-item label="起点地址" prop="startaddress">
        <el-input
          v-model="form.startaddress"
          placeholder="请选择起点地址"
          @focus="showMap('start')">
        </el-input>
      </el-form-item>

      <el-form-item label="配送地址" prop="deliveryAddress">
        <el-input
          v-model="form.deliveryAddress"
          placeholder="请选择配送地址"
          @focus="showMap('end')">
        </el-input>
      </el-form-item>

      <el-form-item label="收货人" prop="consigneeName">
        <el-input v-model="form.consigneeName" placeholder="请输入收货人姓名"></el-input>
      </el-form-item>

      <el-form-item label="联系电话" prop="contactTelOne">
        <el-input v-model="form.contactTelOne" placeholder="请输入联系电话"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">创建物流单</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 地址选择地图弹窗 -->
    <el-dialog 
      title="选择地址" 
      :visible.sync="mapVisible"
      width="80%">
      <div class="map-container">
        <div class="search-box">
          <el-input
            v-model="searchAddress"
            placeholder="搜索地址"
            @keyup.enter.native="searchLocation">
            <el-button 
              slot="append" 
              icon="el-icon-search"
              @click="searchLocation">
            </el-button>
          </el-input>
        </div>
        <div id="map" style="height: 400px;"></div>
      </div>
      <div slot="footer">
        <el-button @click="mapVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CreateLogistics',
  data() {
    return {
      form: {
        trackingNumber: '',
        carrierName: '',
        startaddress: '',
        startlng: '',
        startlat: '',
        deliveryAddress: '',
        endlng: '',
        endlat: '',
        consigneeName: '',
        contactTelOne: ''
      },
      rules: {
        trackingNumber: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        carrierName: [
          { required: true, message: '请输入物流公司', trigger: 'blur' }
        ],
        startaddress: [
          { required: true, message: '请选择起点地址', trigger: 'blur' }
        ],
        deliveryAddress: [
          { required: true, message: '请选择配送地址', trigger: 'blur' }
        ],
        consigneeName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        contactTelOne: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      },
      mapVisible: false,
      map: null,
      marker: null,
      searchAddress: '',
      currentType: '', // 'start' 或 'end'
      selectedLocation: null
    }
  },

  methods: {
    showMap(type) {
      this.currentType = type;
      this.mapVisible = true;
      this.searchAddress = '';
      this.$nextTick(() => {
        if (!this.map) {
          this.initMap();
        }
        if (this.marker) {
          this.map.removeOverlay(this.marker);
        }
      });
    },

    initMap() {
      this.map = new BMap.Map("map");
      const point = new BMap.Point(118.861806, 32.069432);
      this.map.centerAndZoom(point, 14);
      this.map.addControl(new BMap.NavigationControl());
      this.map.addControl(new BMap.ScaleControl());
      this.map.enableScrollWheelZoom();

      this.map.addEventListener('click', (e) => {
        this.setMarker(e.point);
      });
    },

    setMarker(point) {
      if (this.marker) {
        this.map.removeOverlay(this.marker);
      }
      this.marker = new BMap.Marker(point);
      this.map.addOverlay(this.marker);
      this.selectedLocation = point;

      // 解析地址
      const myGeo = new BMap.Geocoder();
      myGeo.getLocation(point, (result) => {
        if (result) {
          this.searchAddress = result.address;
        }
      });
    },

    searchLocation() {
      if (!this.searchAddress) return;
      
      const myGeo = new BMap.Geocoder();
      myGeo.getPoint(this.searchAddress, (point) => {
        if (point) {
          this.map.centerAndZoom(point, 16);
          this.setMarker(point);
        } else {
          this.$message.error('未找到该地址');
        }
      }, "中国");
    },

    confirmLocation() {
      if (!this.selectedLocation || !this.searchAddress) {
        this.$message.warning('请先选择位置');
        return;
      }

      if (this.currentType === 'start') {
        this.form.startaddress = this.searchAddress;
        this.form.startlng = this.selectedLocation.lng.toString();
        this.form.startlat = this.selectedLocation.lat.toString();
      } else {
        this.form.deliveryAddress = this.searchAddress;
        this.form.endlng = this.selectedLocation.lng.toString();
        this.form.endlat = this.selectedLocation.lat.toString();
      }

      this.mapVisible = false;
    },

    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const resp = await this.$axios.post('/apib/api/logistics/create', this.form);
            if (resp.data.code === 200) {
              this.$message.success('创建物流单成功');
              this.resetForm();
              this.$emit('created'); // 通知父组件创建成功
            } else {
              this.$message.error(resp.data.msg || '创建物流单失败');
            }
          } catch (error) {
            console.error('创建物流单失败:', error);
            this.$message.error('创建物流单失败');
          }
        }
      });
    },

    resetForm() {
      this.$refs.form.resetFields();
    }
  }
}
</script>

<style scoped>
.create-logistics {
  padding: 20px;
}

.map-container {
  position: relative;
}

.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  z-index: 1;
}
</style> 